const Router = require('@koa/router');
let router = new Router();
const mongoose = require('mongoose');



router.get('/',async(ctx)=>{
    ctx.body="这是用户操作页面"
});

router.post('/register',async(ctx)=>{
    console.log(ctx.request.body);
    //ctx.body= " 用户注册接口"
    ctx.body = ctx.request.body;
    //取得Model
    const User = mongoose.model('User');
    //把从前端接收的post数据封装成一个新的user对象
    let newUser = new User(ctx.request.body);
    //用mongoose的save方法直接存储，然后判断是否成功，返回相应的结果；
    await newUser.save().then(()=>{
        console.log('插入了');
        ctx.body={
            code:200,
            message:'注册成功'
        }
    }).catch(error=>{
        ctx.body = {
            code:500,
            message:error
            
        }
    })
});

//登录
router.post('/login',async(ctx)=>{
    //得到前端传递过来的数据
    let loginUser = ctx.request.body;
    console.log(loginUser);
    let userName = loginUser.userName;
    let password = loginUser.password;
    //引入user的model
    const User = mongoose.model('User');
    //查找用户名是否存在，如果存在开始比对密码
    await User.findOne({userName:userName}).exec().then(async(result)=>{
        console.log(result)
        if(result){
            console.log(User);
            let newUser = new User();
            await newUser.comparePassword(password,result.password)
            .then( isMatch => {
                //返回对比结果
                ctx.body = { code:200, message:isMatch}
            })
            .catch( error => {
                //出现异常
                console.log(error);
                ctx.body={ code:500, message:error}
            })
        }else{
            ctx.body ={
                code:200, message:'用户名不存在'
            }
        }
    })
})

module.exports=router;